package apk.yoursms.download;

import java.io.IOException;
import java.util.ArrayList;

import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import apk.yoursms.R;
import apk.yoursms.YourSmsActivity;
import apk.yoursms.database.SmsDbHelper;

public class ContentAdapter {

    private final int SMS_LOVE = 1;
    private final int SMS_SKANDAL = 2;
    private final int SMS_CONG = 3;
    private final int SMS_HUMOR = 4;
    private YourSmsActivity activity;

    public ContentAdapter() {
    }

    public ContentAdapter(YourSmsActivity yourSmsActivity) {
	this.activity = yourSmsActivity;
    }

    public void updateList(int ctg) {
	synchronized (activity) {

	    Log.d("CONTENT ADAPTER", "" + ctg);
	    ArrayList<String> content = null;
	    try {
		content = getList(ctg);
	    } catch (IOException e) {
		e.printStackTrace();
	    }

	    String mTitle = null;
	    switch (ctg) {
	    case SMS_LOVE:
		mTitle = activity.getString(R.string.sms_love);
		break;

	    case SMS_SKANDAL:
		mTitle = activity.getString(R.string.sms_skandal);
		break;

	    case SMS_CONG:
		mTitle = activity.getString(R.string.sms_congratulations);
		break;

	    case SMS_HUMOR:
		mTitle = activity.getString(R.string.sms_humor);
		break;

	    default:
		break;
	    }

	    boolean found = false;
	    int index = 0;
	    Log.d("CONTENT ADAPTER", "" + YourSmsActivity.titles);
	    for (int i = 0; i < YourSmsActivity.titles.size(); i++) {
		if (YourSmsActivity.titles.get(i).equalsIgnoreCase(mTitle)) {
		    index = i;
		    found = true;
		    break;
		}
	    }
	    
	    if (content != null) {
		if (found) {
		    YourSmsActivity.contents.put(index, content);
		} else {
		    YourSmsActivity.titles.add(mTitle);
		    index = YourSmsActivity.titles.size() - 1;
		    YourSmsActivity.contents.put(index, content);
		}
	    }
	}
    }

    private ArrayList<String> getList(int category) throws IOException {
	ArrayList<String> list = new ArrayList<String>();
	ArrayList<String> arrayCtg = new ArrayList<String>();

	Cursor cursor = activity.getContentResolver().query(
		Uri.parse("content://apk.yoursms.database.SmsProvider/"
			+ activity.getString(R.string.tableName)), null,
		SmsDbHelper.SMS_CATEGORY + "=" + category, null, null);
	cursor.moveToFirst();

	if (cursor.getCount() != 0) {
	    do {
		String c = cursor.getString(1);
		if (!arrayCtg.contains(c)) {
		    arrayCtg.add(c);
		}
	    } while (cursor.moveToNext());
	    cursor.close();

	    for (String l : arrayCtg) {
		list.add(l);
	    }
	    return list;

	} else {
	    cursor.close();
	}
	return null;

    }

}
